package com.ezops.poc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.ezops.poc.bo.Asset;
import com.ezops.poc.bo.Client;

/**
 * DAO for accesing lookupable items.
 * 
 * @author vgaurav
 * 
 */
@Repository
public class UtilityDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	private static final String GET_ALL_CLIENTS = "SELECT CLIENT_ID, CLIENT_NAME FROM EZOPSDB.CLIENT_LOOKUP";
	private static final String GET_ALL_ASSETS = "SELECT ASSET_ID, ASSET_NAME FROM EZOPSDB.ASSETLOOKUP";

	private static final String GET_BATCH_ID = "SELECT PROPERTY_VALUE FROM EZOPSDB.SYSTEM_PROPERTY WHERE PROPERTY_NAME ='BATCH_ID'";
	private static final String SET_NEXT_BATCH_ID = "UPDATE EZOPSDB.SYSTEM_PROPERTY SET PROPERTY_VALUE=?  WHERE PROPERTY_NAME ='BATCH_ID'";

	private static final String GET_EZOPS_ID = "SELECT PROPERTY_VALUE FROM EZOPSDB.SYSTEM_PROPERTY WHERE PROPERTY_NAME ='EZOPS_ID'";
	private static final String SET_NEXT_EZOPS_ID = "UPDATE EZOPSDB.SYSTEM_PROPERTY SET PROPERTY_VALUE=?  WHERE PROPERTY_NAME ='EZOPS_ID'";

	public UtilityDAO() {
	}

	public List<Client> getAllClients() {
		List<Client> results = jdbcTemplate.query(GET_ALL_CLIENTS,
				new RowMapper<Client>() {

					@Override
					public Client mapRow(ResultSet rs, int arg1)
							throws SQLException {
						Client client = new Client();
						client.setClientId(rs.getInt("CLIENT_ID"));
						client.setClientName(rs.getString("CLIENT_NAME"));
						return client;
					}
				});
		return results;

	}

	public List<Asset> getAllAssets() {
		List<Asset> results = jdbcTemplate.query(GET_ALL_ASSETS,
				new RowMapper<Asset>() {

					@Override
					public Asset mapRow(ResultSet rs, int arg1)
							throws SQLException {
						Asset asset = new Asset();
						asset.setAssetId(rs.getInt("ASSET_ID"));
						asset.setAssetName(rs.getString("ASSET_NAME"));
						return asset;
					}
				});
		return results;

	}

	/**
	 * Get the next batch ID.
	 * 
	 * @return
	 */
	public synchronized int getNextBatchId() {
		int currentBatchId = jdbcTemplate.queryForInt(GET_BATCH_ID);
		int nextBatchId = currentBatchId + 1;
		jdbcTemplate.update(SET_NEXT_BATCH_ID, nextBatchId);
		return nextBatchId;
	}

	/**
	 * Get the next EZOPS ID.
	 * 
	 * @return
	 */
	public synchronized int getNextEzopsId() {
		int currentEzopsId = jdbcTemplate.queryForInt(GET_EZOPS_ID);
		int nextEzopsId = currentEzopsId + 1;
		jdbcTemplate.update(SET_NEXT_EZOPS_ID, nextEzopsId);
		return nextEzopsId;
	}

}
